package org.td.engine.entity;

import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector2;
import org.td.engine.combat.Target;

public class Projectile extends Entity {

    private Target target;
    private float velX;
    private float velY;
    
    private ProjectileClass projectileClass;
    
    public Projectile(EntityEnvironment environment, ProjectileClass projectileClass, float x, float y, Target target) {
        super(environment, projectileClass);
        this.x = x;
        this.y = y;
        this.target = target;
        this.projectileClass = projectileClass;
    }
    
    public void setTarget(Target target) {
        this.target = target;
    }

    @Override
    public void update(float time) {
        Vector2 rad = new Vector2(target.getX() - x, target.getY() - y);
        rad = rad.nor();
        float speed = projectileClass.getSpeed() * time;

        
        double dist = Math.sqrt((target.getX() - x)*(target.getX() - x) + (target.getY() - y)*(target.getY() - y));
        boolean reached = false;
        if (dist <= speed + 5.0f) {
            speed = (float)dist;
            reached = true;
        }
        velX = rad.x * speed;
        velY = rad.y * speed;

        x += velX;
        y += velY;

        if (reached) {
            projectileClass.getOnHitEffect().apply(this, target);
            clear = true;
        }
    }

    @Override
    public void render(SpriteBatch batch) {
        float angle = (float)Math.toDegrees(Math.atan2(velY, velX));

        sprite.setRotation(angle);
        sprite.render(batch, x, y, true);
    }
    
    @Override
    public EntityClass getEntityClass() {
        return projectileClass;
    }
    
}
